package cn.netswap.jeegorilla.framework.security.social;

import cn.netswap.jeegorilla.framework.security.social.BaseSocalProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.social.UserIdSource;
import org.springframework.social.config.annotation.EnableSocial;
import org.springframework.social.config.annotation.SocialConfigurerAdapter;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.connect.jdbc.JdbcUsersConnectionRepository;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.social.security.AuthenticationNameUserIdSource;

import javax.sql.DataSource;

/**
 * @author lgw
 * @version 1.0
 * @date 2020/3/24 14:00
 */
@Configuration
@EnableSocial
public class SocialAdapter extends SocialConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Autowired(required = false)
    private ConnecitonSignUp gorillaConnecitonSignUp;

    @Autowired
    private BaseSocalProperties properties;

    @Bean
    public ProviderSignInUtils providerSignInUtils(ConnectionFactoryLocator connectionFactoryLocator) {
        return new ProviderSignInUtils(connectionFactoryLocator, getUsersConnectionRepository(connectionFactoryLocator));
    }

    @Bean
    public SocialConfigurer gorillaSocialConfigurer() {
        SocialConfigurer springSocialConfigurer = new SocialConfigurer(properties.getFilterProcessesUrl());
        springSocialConfigurer.userIdSource(getUserIdSource());
        springSocialConfigurer.signupUrl(properties.getSignupUrl());
        return springSocialConfigurer;
    }

    @Primary
    @Bean
    @Override
    public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
        // Encryptors.noOpText() 对数据不加密
        JdbcUsersConnectionRepository jdbcUsersConnectionRepository = new JdbcUsersConnectionRepository(dataSource, connectionFactoryLocator, Encryptors.noOpText());
        // 只能设置表前缀，但是不能修改表名
        jdbcUsersConnectionRepository.setTablePrefix("");
        if (gorillaConnecitonSignUp != null) {
            jdbcUsersConnectionRepository.setConnectionSignUp(gorillaConnecitonSignUp);
        }
        return jdbcUsersConnectionRepository;
    }

    @Override
    public UserIdSource getUserIdSource() {
        return new AuthenticationNameUserIdSource();
    }
}
